﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using UtilZ.Dotnet.Ex.ZLog;

namespace UtilZ.Dotnet.Ex.Base
{
    /// <summary>
    /// 线程启动参数
    /// </summary>
    internal sealed class ThreadStartPara : IDisposable
    {
        /// <summary>
        /// 参数对象
        /// </summary>
        public object Obj { get; private set; }

        private readonly CancellationTokenSource _cts;
        /// <summary>
        /// CancellationTokenSource
        /// </summary>
        public CancellationTokenSource Cts
        {
            get { return _cts; }
        }


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="obj">参数对象</param>
        public ThreadStartPara(object obj)
        {
            this.Obj = obj;
            this._cts = new CancellationTokenSource();
        }


        private bool _cancel = false;
        private bool _disposed = false;

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            lock (this)
            {
                if (this._disposed)
                {
                    return;
                }
                this._disposed = true;

                if (!this._cancel)
                {
                    this._cts.Cancel();
                }

                this._cts.Dispose();
            }
        }

        /// <summary>
        /// 取消执行
        /// </summary>
        public void Cancell()
        {
            lock (this)
            {
                if (this._disposed)
                {
                    return;
                }

                this._cts.Cancel();
                this._cancel = true;
            }
        }

    }

}
